//
//  ChartViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-2-26.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "ChartViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "AppDelegate.h"
#import "asyncimageview.h"
#import "MainTabBarController.h"
#import "LoginViewController.h"
#import "WriteDDViewController.h"
@interface ChartViewController ()

@end

@implementation ChartViewController

- (id)init
{
    if (self = [super init]) {
        // Custom initialization
        _BusProArr = [[NSMutableArray alloc] init];
        _AsyImgArr = [[NSMutableArray alloc] init];
        _SelectArr = [[NSMutableArray alloc] init];
        _IsRequested = NO;
        
         _NoneImg= [[UIImage imageNamed:@"select.png"] retain];
        _SelectImg = [[UIImage imageNamed:@"checked.png"] retain];
    }
    return self;
}

-(void) dealloc
{
    [_SelectArr release];
    [_SelectImg release];
    [_NoneImg release];
    [_AsyImgArr release];
    [_BusProArr release];
    [_TableView release];
    [_NavBtt release];
    [_ResBtt release];
    [m_titleBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
//    UILabel* tNavTitleLab = (UILabel*)[self.navigationController.navigationBar viewWithTag:144];
//    [tNavTitleLab setText:@"购物车"];
    m_titleBttBarItem = [[MainTabBarController setTitle:@"购物车"] retain];
    _NavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_NavBtt setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [_NavBtt addTarget:self action:@selector(navPopPressed) forControlEvents:UIControlEventTouchUpInside];
    _NavBtt.frame =CGRectMake(4, 7, 50, 30);
    [_NavBtt retain];
    UILabel* tBackLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 5, 30, 20)];
    [tBackLab setBackgroundColor:[UIColor clearColor]];
    [tBackLab setTextColor:[UIColor whiteColor]];
    [tBackLab setText:@"返回"];
    [tBackLab setFont:[UIFont systemFontOfSize:13]];
    [_NavBtt addSubview:tBackLab];
    [tBackLab release];
    
    _ResBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_ResBtt setTitle:@"去结算" forState:UIControlStateNormal];
    _ResBtt.frame =CGRectMake(self.navigationController.navigationBar.frame.size.width-55, 7, 50, 30);
    [_ResBtt setBackgroundImage:[UIImage imageNamed:@"button_right.png"] forState:UIControlStateNormal];
    [_ResBtt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _ResBtt.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [_ResBtt addTarget:self action:@selector(resBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [_ResBtt retain];
    
    
    _TableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height) style:UITableViewStylePlain];
    _TableView.delegate = self;
    _TableView.dataSource = self;
    [self.view addSubview:_TableView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar addSubview:_NavBtt];
    [self.navigationController.navigationBar addSubview:_ResBtt];
     [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
    if (!_IsRequested) {
        [self requestDetailData];
    }
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_NavBtt removeFromSuperview];
    [_ResBtt removeFromSuperview];
    [m_titleBttBarItem removeFromSuperview];
}

-(void) navPopPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}

//结算
-(void) resBttPressed
{
    NSMutableString* tTmpStr = [NSMutableString string];
    NSMutableString* tTmpStr1 = [NSMutableString string];
    WriteDDViewController* tWriteDDVC = [[WriteDDViewController alloc] init];
    tWriteDDVC.m_ProPrice = [NSString stringWithFormat:@"%d",_PriveNum];
    
    for (NSDictionary* tDic in _BusProArr) {
        [tTmpStr appendString:@"1"];
        [tTmpStr appendString:@","];
        
        [tTmpStr1 appendString:[NSString stringWithFormat:@"%d",[[tDic objectForKey:@"id"] intValue]]];
        [tTmpStr1 appendString:@","];
    }
    
    if ([tTmpStr length] > 0) {
        [tTmpStr deleteCharactersInRange:NSMakeRange([tTmpStr length]-1, 1)];
        [tTmpStr1 deleteCharactersInRange:NSMakeRange([tTmpStr length]-1, 1)];
        tWriteDDVC.m_ProdNums =tTmpStr;
        tWriteDDVC.m_ProdIDs =tTmpStr1;
        tWriteDDVC.navigationItem.hidesBackButton =YES;
        [self.navigationController pushViewController:tWriteDDVC animated:YES];
        [tWriteDDVC release];
    } else {
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"请先选择商品" detailText:@"" isCue:-1 delayTime:2];
    }
}

//去逛逛
-(void) ggBttPressed
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark-
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([[_SelectArr objectAtIndex:indexPath.row] isEqualToString:@"1"]) {
        [_SelectArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
    }else{
        [_SelectArr replaceObjectAtIndex:indexPath.row withObject:@"1"];
    }
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 64;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ([_BusProArr count] > 0) {
        return 40;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* tSectionHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    [tSectionHeader setBackgroundColor:[UIColor colorWithRed:200/255.f green:200/255.f blue:200/255.f alpha:1]];
    UILabel* tTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, 100, 20)];
    [tTitleLab setBackgroundColor:[UIColor clearColor]];
    [tTitleLab setFont:[UIFont systemFontOfSize:13]];
    [tTitleLab setText:@"商品金额总计"];
    [tSectionHeader addSubview:tTitleLab];
    [tTitleLab release];
    
    UILabel* tPriceLab = [[UILabel alloc] initWithFrame:CGRectMake(100, 10, 100, 20)];
    [tPriceLab setBackgroundColor:[UIColor clearColor]];
    [tPriceLab setFont:[UIFont systemFontOfSize:13]];
    [tPriceLab setTextColor:[UIColor colorWithRed:251/255.f green:154/255.f blue:3/255.f alpha:1]];
    [tPriceLab setText:[NSString stringWithFormat:@"¥ %d",_PriveNum]];
    [tSectionHeader addSubview:tPriceLab];
    [tPriceLab release];
    return [tSectionHeader autorelease];
}
#pragma mark-
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_BusProArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* tNameCell  =@"norcell";
    int tRow = indexPath.row;
    UITableViewCell* tCell = [tableView dequeueReusableCellWithIdentifier:tNameCell];
    if (tCell == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tNameCell] autorelease];
        UILabel* tTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(62, 6, 220,20)];
        [tTitleLab setBackgroundColor:[UIColor clearColor]];
        [tTitleLab setFont:[UIFont boldSystemFontOfSize:13]];
        tTitleLab.tag =50;
        [tCell addSubview:tTitleLab];
        [tTitleLab release];
        
        UILabel* tDesLab = [[UILabel alloc] initWithFrame:CGRectMake(62, 22, 240,24)];
        [tDesLab setBackgroundColor:[UIColor clearColor]];
        [tDesLab setTextColor:[UIColor colorWithRed:251/255.f green:153/255.f blue:0 alpha:1]];
        [tDesLab setFont:[UIFont systemFontOfSize:18]];
        tDesLab.tag =51;
        [tCell addSubview:tDesLab];
        [tDesLab release];
        
        UIImageView* tSelectImg = [[UIImageView alloc] initWithFrame:CGRectMake(280, 18, 20, 20)];
        tSelectImg.tag =52;
        [tCell addSubview:tSelectImg];
        [tSelectImg release];
    }
    for (id tSubObject in tCell.subviews) {
        if ([tSubObject isKindOfClass:[AsyncImageView class]]) {
            [tSubObject removeFromSuperview];
        }
    }
    id tAsyObject = [_AsyImgArr objectAtIndex:tRow];
    BOOL tIsHaveImg =NO;
    if ([tAsyObject isKindOfClass:[AsyncImageView class]]) {
        [tCell addSubview:tAsyObject];
        [tAsyObject customLoadImageFromURL];
        tIsHaveImg = YES;
    }
    UILabel* tTitleLab = (UILabel*)[tCell viewWithTag:50];
    UILabel* tDesLab = (UILabel*)[tCell viewWithTag:51];
    UIImageView* tImgView = (UIImageView*)[tCell viewWithTag:52];
    NSDictionary* tBookDic = [_BusProArr objectAtIndex:tRow];
    [tTitleLab setText:[tBookDic objectForKey:@"name"]];
    [tDesLab setText:[NSString stringWithFormat:@"¥ %d",[[tBookDic objectForKey:@"price"] intValue]]];
    if ([[_SelectArr objectAtIndex:tRow] isEqualToString:@"1"]) {
        [tImgView setImage:_SelectImg];
    }else{
        [tImgView setImage:_NoneImg];
    }
    return tCell;
}



-(void) requestAddChartFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            _PriveNum = [[tRealDataDic objectForKey:@"total_price"] intValue];
            [_BusProArr addObjectsFromArray:[tRealDataDic objectForKey:@"list"]];
            for (NSDictionary* tDic in _BusProArr) {
                NSString* tImgURL = [tDic objectForKey:@"image"];
                AsyncImageView* tImgView = [[AsyncImageView alloc] initWithFrame:CGRectMake(6, 6, 50, 50)];
                tImgView.m_BoolSetImage =YES;
                tImgView._numStateRequested =need_Request;
                tImgView._imageRequestURL =tImgURL;
                [_AsyImgArr addObject:tImgView];
                [tImgView customLoadImageFromURL];
                [tImgView release];
                
                [_SelectArr addObject:@"1"];
            }
            
            [_TableView reloadData];
            
            if ([_BusProArr count] == 0) {
                UIView* tBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
                [tBGView setBackgroundColor:[UIColor colorWithRed:245/255.f green:245/255.f blue:245/255.f alpha:1]];
                [self.view addSubview:tBGView];
                [tBGView release];
                
                UIImageView* tImgView = [[UIImageView alloc]initWithFrame:CGRectMake(122, 120, 75, 54)];
                [tImgView setImage:[UIImage imageNamed:@"cart_empty.png"]];
                [tBGView addSubview:tImgView];
                [tImgView release];
                UILabel* tDeslab = [[UILabel alloc] initWithFrame:CGRectMake(0, 180, 320, 20)];
                [tDeslab setBackgroundColor:[UIColor clearColor]];
                [tDeslab setText:@"您还没有购买商品"];
                [tDeslab setTextColor:[UIColor colorWithRed:152/255.f green:152/255.f blue:152/255.f alpha:1]];
                [tDeslab setFont:[UIFont boldSystemFontOfSize:14]];
                tDeslab.textAlignment = UITextAlignmentCenter;
                [tBGView addSubview:tDeslab];
                [tDeslab release];
                
                UIButton* tGGBtt = [UIButton buttonWithType:UIButtonTypeCustom];
                [tGGBtt setImage:[UIImage imageNamed:@"button_gray_s.png"] forState:UIControlStateNormal];
                tGGBtt.frame =CGRectMake(105, 210, 110, 28);
                [tGGBtt addTarget:self action:@selector(ggBttPressed) forControlEvents:UIControlEventTouchUpInside];
                [tBGView addSubview:tGGBtt];
                
                UILabel* tBttlab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 110, 28)];
                [tBttlab setBackgroundColor:[UIColor clearColor]];
                [tBttlab setText:@"马上去逛逛"];
                [tBttlab setFont:[UIFont boldSystemFontOfSize:14]];
                tBttlab.textAlignment = UITextAlignmentCenter;
                [tGGBtt addSubview:tBttlab];
                [tBttlab release];
            }
        }else{
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:-1 delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    _IsRequested = YES;
    [self hudWasHidden:nil];
}

-(void) requestDetailData
{
    
    MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;

    [self addHudLoad];
    NSDictionary* tDataDic = [tMainTabController.m_UserDic objectForKey:@"data"];
    NSString* tURLStr = nil;
    if ([[tDataDic objectForKey:@"user_id"] length] > 0) {
        tURLStr = [NSString stringWithFormat:@"%@ac=getCartList&cur_user_id=%@&UDID=%@",RequestCurrentURL,[tDataDic objectForKey:@"user_id"],[UIDevice currentDevice].uniqueIdentifier];
    }else{
        tURLStr = [NSString stringWithFormat:@"%@ac=getCartList&UDID=%@",RequestCurrentURL,[UIDevice currentDevice].uniqueIdentifier];
    }
    
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tURLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestDetailFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestAddChartFinish:)];
    [tRequestPage startAsynchronous];

}

-(void) requestDetailFail:(ASIHTTPRequest*)request
{

    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}
@end
